package cn.lastcrdg.testitemdecoration;

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.support.v7.widget.RecyclerView;
import android.view.View;

/**
 * author：liluo
 * e-mail：lastcrazysun@163.com
 * company：cusc
 * date：2018/4/8 18:00
 * description：自定义时间轴分割线
 */
public class TimeLineItemDecoration extends RecyclerView.ItemDecoration{

    private int circleRadius = 30;
    private int dividerLeft = 160;
    private int dividerTop = 10;
    private Paint mPaint;

    public TimeLineItemDecoration() {
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setColor(Color.RED);
        mPaint.setStrokeWidth(4);
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);

        if (parent.getChildAdapterPosition(view) != 0) {
            outRect.top = dividerTop;
        }
        outRect.left = dividerLeft;
    }

    @Override
    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
        super.onDraw(c, parent, state);

        int count = parent.getChildCount();
        int centerX = dividerLeft/2 + parent.getPaddingLeft();
        int lineX = centerX;

        for (int i = 0; i < count; i++) {
            View view = parent.getChildAt(i);

            int index = parent.getChildAdapterPosition(view);

            int centerY = view.getBottom() - view.getMeasuredHeight()/2;

            int topLineStartY = view.getTop() - dividerTop;
            int topLineEndY = centerY - circleRadius;

            if (index != 0) {
                //第一条没有上线
                c.drawLine(lineX, topLineStartY, lineX, topLineEndY, mPaint);
            }

            mPaint.setStyle(Paint.Style.STROKE);
            c.drawCircle(centerX, centerY, circleRadius, mPaint);

            int bottomLineStartY = centerY + circleRadius;
            int bottomLineEndY = view.getBottom() + view.getPaddingBottom();

            if (index != parent.getAdapter().getItemCount()-1) {
                //最后一个每有下线
                c.drawLine(lineX, bottomLineStartY, lineX, bottomLineEndY, mPaint);
            }
        }

    }

    @Override
    public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
        super.onDrawOver(c, parent, state);

        int centerX = dividerLeft/2 + parent.getPaddingLeft();
        int count = parent.getChildCount();
        for (int i = 0; i < count; i++) {
            View view = parent.getChildAt(i);
            int centerY = view.getBottom() - view.getMeasuredHeight()/2;
            c.drawCircle(centerX*2, centerY, circleRadius , mPaint);
        }
    }
}
